from PIL import Image, ImageFilter, ImageFont, ImageDraw
import random
from io import BytesIO
width = 100
height = 40
# 最后一个参数是背景颜色
img = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(img)


# 获取颜色
def get_color():
    return random.randint(200, 255), random.randint(200, 255), random.randint(200, 255)


# 获取一个字母或数字
def get_chart():
    return chr(random.randint(65, 90))


def get_image():
    # 填充每一个像素
    for x in range(width):
        for y in range(height):
            draw.point((x, y), fill=get_color())

    font = ImageFont.truetype('simsun.ttc', 36)
    code=[]
    for i in range(4):
        a=get_chart()
        code.append(a)
        draw.text((10 + i * 20, 5), a, font=font, fill=(255, 0, 0))
    # 干扰线
    for i in range(2):
        draw.line(((10, 10), (80, 30)), fill=(0, 255, 0), width=3)
    #img.show()
    return img,''.join(code)

if __name__ == '__main__':
    stream=BytesIO()
    im,code=get_image()
    #在文件中保存
    with open('code.png','wb') as f:
        im.save(f,format='png')
    #在内容中保存
    # im.save(stream,'png')
    #获取内存中的图片内容
    # stream.getvalue()